<template>
  <div class="wh-full flex overflow-hidden bg-bg_color">
    <sidebar :active="module" v-if="module"></sidebar>
    <article class="flex-1 flex-col w-0">
      <app-header
        :menus="breadcrumb"
        v-if="route.name != 'Discover'"
        class="h-64 auto-bg"
        border-b="1px solid normal_border"
      ></app-header>
      <div class="flex-1 overflow-hidden flex">
        <navigation
          v-if="menu && (menu!.children || []).length > 0"
          :list="menu.children || []"
          class="w-192 auto-bg"
          border-r="1px solid normal_border"
        ></navigation>
        <main class="flex-1 cus-scroll-y">
          <slot></slot>
        </main>
      </div>
    </article>
  </div>
</template>

<script setup lang="ts">
import sidebar from './sidebar/sidebar.vue'
import { usePermissionStore } from '@/store'
import AppHeader from '@/layouts/normal/header/app-header.vue'
import { PermissionDto } from '@/api/permission.ts'
import Navigation from '@/layouts/normal/navigation/navigation.vue'

const route = useRoute()
const { menus, permissions } = usePermissionStore()

const getParent = (name: string): string => {
  const permission = permissions.find((p) => p.code == name)
  if (permission && permission!.parentId) {
    const parent = permissions.find((p) => p.id == permission.parentId)
    if (parent) {
      return getParent(parent.code!)
    } else {
      return name
    }
  } else {
    return name
  }
}

const getPermission = (code: string) => {
  return permissions.find((p) => p.code == code)
}

const module = computed(() => {
  const name = route.meta?.parentKey || route.name
  return getParent(name as string)
})

const breadcrumb = computed(() => {
  const list: PermissionDto[] = []
  const loop = (name: string) => {
    const permission = getPermission(name as string)
    if (permission) {
      list.splice(0, 0, permission)
      if (permission.parentId) {
        const parent = permissions.find((p) => p.id == permission.parentId)
        if (parent && parent.code) {
          loop(parent.code!)
        }
      }
    }
  }

  loop(route.name as string)
  return list
})

const menu = computed(() => {
  return menus.find((menu) => menu.key == module.value)
})

// const module = computed(() => {
//   debugger
//   return menu.value?.nodes[0]
// })
</script>
